//
//  MSTagsView.m
//  PeopleForTheFirstMall
//
//  Created by ms on 2022/5/7.
//  Copyright © 2022 MS. All rights reserved.
//

#import "MSTagsView.h"

@interface MSTagsView ()

@property (nonatomic, strong) UIView *lineView;
@property (nonatomic, strong) UIView *stickersView;
@property (nonatomic) NSTimeInterval kLastTime;

@end

@implementation MSTagsView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:CGRectMake(0, 0, MAXFLOAT, MAXFLOAT)];
    self.itemSpace = 49 * MS_ADAPTATION_RATIO;
    self.insets = UIEdgeInsetsZero;
    self.idxForSelectedItem = 0;
    self.hiddenSubtitle = YES;
    self.insertStickers = NO;
    self.autoScrollToCenter = YES;
    return self;
}

- (void)didSelectITem:(UIButton *)sender
{
    BOOL b = (NSDate.date.timeIntervalSince1970 - self.kLastTime) >= 1;
    if (!b) return;
    //保存上次点击时间
    self.kLastTime = NSDate.date.timeIntervalSince1970;
    
    UIButton *btn = [self viewWithTag:self.idxForSelectedItem + 1000];
    UIButton *subBtn = [self viewWithTag:self.idxForSelectedItem + 2000];
    self.idxForSelectedItem = sender.tag - 1000;
    UIButton *newSubBtn = [self viewWithTag:self.idxForSelectedItem + 2000];
    //更新标签选中状态
    btn.selected = NO;
    sender.selected = YES;
    //更新标签贴片
    if (self.insertStickers)
    {
        CGFloat stickerBottomToTitle = self.stickerBottomToLabelBlock ? self.stickerBottomToLabelBlock(0) : 0;
        CGFloat stickerRightToTitle = self.stickerRightToLabelBlock ? self.stickerRightToLabelBlock(0) : 0;
        CGSize size = self.stickerSizeBlock ?  self.stickerSizeBlock(0) : CGSizeMake(22 * MS_ADAPTATION_RATIO, 14 * MS_ADAPTATION_RATIO);
        
        [self.stickersView mas_remakeConstraints:^(MASConstraintMaker *make) {
            
            make.bottom.equalTo(sender).offset(stickerBottomToTitle);
            make.right.equalTo(sender).offset(stickerRightToTitle);
            make.size.mas_equalTo(size);
        }];
    }
    // 更新副标题选中状态
    if (!self.hiddenSubtitle)
    {
        subBtn.selected = NO;
        newSubBtn.selected = YES;
    }
    //更新线条位置
    if (!self.hiddenLine)
    {
        CGSize size = self.lineSizeBlock ? self.lineSizeBlock() : CGSizeMake(49 * MS_ADAPTATION_RATIO, 6 * MS_ADAPTATION_RATIO);
        [self.lineView mas_remakeConstraints:^(MASConstraintMaker *make) {
            
            make.size.mas_equalTo(size);
            make.centerX.equalTo(sender);
            if (self.hiddenSubtitle)
            {
                make.top.equalTo(btn.mas_bottom).offset(self.lineToTitleOrSubTitleSpacingBlock ? self.lineToTitleOrSubTitleSpacingBlock() : 8 * MS_ADAPTATION_RATIO);
            }
            else
            {
                make.top.equalTo(subBtn.mas_bottom).offset(self.lineToTitleOrSubTitleSpacingBlock ? self.lineToTitleOrSubTitleSpacingBlock() : 8 * MS_ADAPTATION_RATIO);
            }
        }];
    }
    //滑动到中间
    if (self.autoScrollToCenter)
    {
        CGFloat x = CGRectGetMidX(sender.frame);
        CGFloat width = CGRectGetWidth(self.frame);
        CGFloat contentSize_width = MAX(self.contentSize.width, width);
        if (x - width / 2.0 <= 0)
        {
            [self setContentOffset:CGPointMake(0, 0) animated:YES];
        }
        else if (x - width / 2.0 >= contentSize_width - width)
        {
            [self setContentOffset:CGPointMake(contentSize_width - width, 0) animated:YES];
        }
        else
        {
            [self setContentOffset:CGPointMake(x - width / 2.0, 0) animated:YES];
        }
    }
    // 回调
    if (self.didSelectItemBlock)
    {
        self.didSelectItemBlock(self.idxForSelectedItem);
    }
}
- (void)didSelectSubtitle:(UIButton *)sender
{
    BOOL b = (NSDate.date.timeIntervalSince1970 - self.kLastTime) >= 1;
    if (!b) return;
    //保存上次点击时间
    self.kLastTime = NSDate.date.timeIntervalSince1970;
    
    UIButton *btn = [self viewWithTag:self.idxForSelectedItem + 1000];
    UIButton *subBtn = [self viewWithTag:self.idxForSelectedItem + 2000];
    self.idxForSelectedItem = sender.tag - 2000;
    UIButton *newBtn = [self viewWithTag:self.idxForSelectedItem + 1000];
    //更新标签选中状态
    btn.selected = NO;
    subBtn.selected = NO;
    sender.selected = YES;
    newBtn.selected = YES;
    //更新标签贴片
    if (self.insertStickers)
    {
        CGFloat stickerBottomToTitle = self.stickerBottomToLabelBlock ? self.stickerBottomToLabelBlock(0) : 0;
        CGFloat stickerRightToTitle = self.stickerRightToLabelBlock ? self.stickerRightToLabelBlock(0) : 0;
        CGSize size = self.stickerSizeBlock ?  self.stickerSizeBlock(0) : CGSizeMake(22 * MS_ADAPTATION_RATIO, 14 * MS_ADAPTATION_RATIO);
        
        [self.stickersView mas_remakeConstraints:^(MASConstraintMaker *make) {
            
            make.bottom.equalTo(newBtn).offset(stickerBottomToTitle);
            make.right.equalTo(newBtn).offset(stickerRightToTitle);
            make.size.mas_equalTo(size);
        }];
    }
    //更新线条位置
    if (!self.hiddenLine)
    {
        CGSize size = self.lineSizeBlock ? self.lineSizeBlock() : CGSizeMake(49 * MS_ADAPTATION_RATIO, 6 * MS_ADAPTATION_RATIO);
        [self.lineView mas_remakeConstraints:^(MASConstraintMaker *make) {
            
            make.size.mas_equalTo(size);
            make.centerX.equalTo(newBtn);
            make.top.equalTo(sender.mas_bottom).offset(self.lineToTitleOrSubTitleSpacingBlock ? self.lineToTitleOrSubTitleSpacingBlock() : 8 * MS_ADAPTATION_RATIO);
        }];
    }
    //滑动到中间
    if (self.autoScrollToCenter)
    {
        CGFloat x = CGRectGetMidX(newBtn.frame);
        CGFloat width = CGRectGetWidth(self.frame);
        CGFloat contentSize_width = MAX(self.contentSize.width, width);
        if (x - width / 2.0 <= 0)
        {
            [self setContentOffset:CGPointMake(0, 0) animated:YES];
        }
        else if (x - width / 2.0 >= contentSize_width - width)
        {
            [self setContentOffset:CGPointMake(contentSize_width - width, 0) animated:YES];
        }
        else
        {
            [self setContentOffset:CGPointMake(x - width / 2.0, 0) animated:YES];
        }
    }
    // 回调
    if (self.didSelectItemBlock)
    {
        self.didSelectItemBlock(self.idxForSelectedItem);
    }
}


- (void)reloadTagsView
{
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    NSInteger number = self.numberOfLabelsInTagsViewBlock ? self.numberOfLabelsInTagsViewBlock() : 0;
    for (int i = 0; i < number; i++)
    {
        UIImage *unselectedItemBackgroundImage = self.unselectedLabelBackgroundImageBlock ? self.unselectedLabelBackgroundImageBlock(i) : nil;
        UIImage *selectedItemBackgroundImage = self.selectedLabelBackgroundImageBlock ? self.selectedLabelBackgroundImageBlock(i) : nil;
        UIFont *title_unselectedfont = self.unselectedLabelTextFontBlock ? self.unselectedLabelTextFontBlock(i) : MS_SYSTEM_FONT_OF_SIZE(16);
        UIFont *title_selectedFont = self.selectedLabelTextFontBlock ? self.selectedLabelTextFontBlock(i) : MS_SYSTEM_FONT_OF_SIZE(17);
        UIColor *title_unselectedColor = self.unselectedLabelTextColorBlock ? self.unselectedLabelTextColorBlock(i) : MS_HEX_COLOR(0xBDBDBD);
        UIColor *title_selectedColor = self.selectedLabelTextColorBlock ? self.selectedLabelTextColorBlock(i) : MS_HEX_COLOR(0x5ED3D2);
        NSString *title = self.titleForItemBlock ? self.titleForItemBlock(i) : @"";
        CGFloat title_w;
        CGFloat title_h;
        if (self.labelSizeBlock)
        {
            CGSize size = self.labelSizeBlock(i);
            title_w = size.width;
            title_h = size.height;
        }
        else
        {
            CGSize size = ms_sizeOfText(title, title_selectedFont);
            UIEdgeInsets edges = self.labelTextInsetsBlock ? self.labelTextInsetsBlock(i) : UIEdgeInsetsMake(1, 1, 1, 1);
            title_w = size.width + edges.left + edges.right;
            title_h = size.height + edges.top + edges.bottom;
        }
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.tag = i + 1000;
        btn.titleLabel.font = title_unselectedfont;
        RAC(btn.titleLabel, font) = [RACObserve(btn, selected) map:^id _Nullable(id  _Nullable value) {
            
            return btn.isSelected ? title_selectedFont : title_unselectedfont;
        }];
        [btn setBackgroundImage:unselectedItemBackgroundImage
                       forState:UIControlStateNormal];
        [btn setBackgroundImage:selectedItemBackgroundImage
                       forState:UIControlStateSelected];
        [btn setTitleColor:title_unselectedColor
                  forState:UIControlStateNormal];
        [btn setTitleColor:title_selectedColor
                  forState:UIControlStateSelected];
        btn.selected = NO;
        [btn setTitle:title
             forState:UIControlStateNormal];
        if (self.labelCornerRadiiBlock)
        {
            CGFloat itemCornerRadii = self.labelCornerRadiiBlock(i);
            btn.layer.cornerRadius = itemCornerRadii;
            btn.layer.masksToBounds = YES;
        }
        [btn addTarget:self
                action:@selector(didSelectITem:)
      forControlEvents:UIControlEventTouchUpInside];
        
        [self addSubview:btn];
        
        [btn mas_remakeConstraints:^(MASConstraintMaker *make) {
            
            make.top.mas_equalTo(self.insets.top);
            if (i == 0)
            {
                make.left.mas_equalTo(self.insets.left);
            }
            else
            {
                UIView *view = [self viewWithTag:i + 1000 - 1];
                make.left.equalTo(view.mas_right).offset(self.itemSpace);
            }
            
            if (i == number - 1)
            {
                make.right.mas_equalTo(-self.insets.right);
            }
            make.width.mas_equalTo(title_w);
            make.height.mas_equalTo(title_h);
        }];
        
        if (!self.hiddenSubtitle)
        {
            NSString *subtitle = self.subtitleForItemBlock ? self.subtitleForItemBlock(i) : @"";
            UIColor *subtitle_color = self.unselectedSubLabelTextColorBlock ? self.unselectedSubLabelTextColorBlock(i) : MS_HEX_COLOR(0xBDBDBD);
            UIColor *subtitle_selectedColor = self.selectedSubLabelTextColorBlock ? self.selectedSubLabelTextColorBlock(i) : MS_HEX_COLOR(0x5ED3D2);
            UIFont *subtitle_font = self.unselectedSubLabelTextFontBlock ? self.unselectedSubLabelTextFontBlock(i) : MS_SYSTEM_FONT_OF_SIZE(16);
            UIFont *subtitle_selectedFont = self.selectedSubLabelTextFontBlock ? self.selectedSubLabelTextFontBlock(i) : MS_SYSTEM_FONT_OF_SIZE(17);
            UIImage *subTextBackgroundImage = self.unselectedSubLabelBackgroundImageBlock ? self.unselectedSubLabelBackgroundImageBlock(i) : nil;
            UIImage *subTextSelectedBackgroundImage = self.selectedSubLabelBackgroundImageBlock ? self.selectedSubLabelBackgroundImageBlock(i) : nil;
            CGFloat subtitle_w = ms_sizeOfText(subtitle, subtitle_selectedFont).width + 26 * MS_ADAPTATION_RATIO;
            CGFloat subtitle_h = ms_sizeOfText(subtitle, subtitle_selectedFont).height + 1;
            if (self.subLabelWidthBlock)
            {
                subtitle_w = self.subLabelWidthBlock(i);
            }
            CGFloat subtitleToTitleSpacing = self.subLabelToLabelSpacingBlock ? self.subLabelToLabelSpacingBlock() : 8 * MS_ADAPTATION_RATIO;
            
            UIButton *subBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            subBtn.tag = i + 2000;
            subBtn.titleLabel.font = subtitle_font;
            [subBtn setBackgroundImage:subTextBackgroundImage
                           forState:UIControlStateNormal];
            [subBtn setBackgroundImage:subTextSelectedBackgroundImage
                           forState:UIControlStateSelected];
            [subBtn setTitleColor:subtitle_color
                      forState:UIControlStateNormal];
            [subBtn setTitleColor:subtitle_selectedColor
                      forState:UIControlStateSelected];
            subBtn.selected = NO;
            [subBtn setTitle:subtitle
                 forState:UIControlStateNormal];
            [subBtn ms_makeChains:^(MSChainMaker * _Nonnull make) {
               
                make.ms_cornerRadii(subtitle_h / 2.0);
            }];
            if (self.subLabelCornerRadiiBlock)
            {
                CGFloat itemCornerRadii = self.subLabelCornerRadiiBlock(i);
                subBtn.layer.cornerRadius = itemCornerRadii;
                subBtn.layer.masksToBounds = YES;
            }
            [subBtn addTarget:self
                    action:@selector(didSelectSubtitle:)
          forControlEvents:UIControlEventTouchUpInside];
            
            [self addSubview:subBtn];
            
            [subBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
                
                make.top.equalTo(btn.mas_bottom).offset(subtitleToTitleSpacing);
                make.width.mas_equalTo(subtitle_w);
                make.height.mas_equalTo(subtitle_h);
                make.centerX.equalTo(btn);
            }];
        }
    }
    
    if (number > 0)
    {
        UIButton *btn = [self viewWithTag:self.idxForSelectedItem + 1000];
        UIButton *subBtn = [self viewWithTag:self.idxForSelectedItem + 2000];
        btn.selected = YES;
        if (!self.hiddenSubtitle)
        {
            subBtn.selected = YES;
        }
        
        if (self.insertStickers)
        {
            //后续如果有需要不同标签使用不同的贴片，创建方法放在上面for循环中即可
            [self insertSubview:self.stickersView atIndex:0];
            UIImage *selectedStickerImage = self.selectedStickerImageBlock ? self.selectedStickerImageBlock(0) : UIImage.new;
            self.stickersView.layer.contents = (id)selectedStickerImage.CGImage;
            CGFloat stickerBottomToTitle = self.stickerBottomToLabelBlock ? self.stickerBottomToLabelBlock(0) : 0;
            CGFloat stickerRightToTitle = self.stickerRightToLabelBlock ? self.stickerRightToLabelBlock(0) : 0;
            CGSize size = self.stickerSizeBlock ?  self.stickerSizeBlock(0) : CGSizeMake(22 * MS_ADAPTATION_RATIO, 14 * MS_ADAPTATION_RATIO);
            
            [self.stickersView mas_remakeConstraints:^(MASConstraintMaker *make) {
                
                make.bottom.equalTo(btn).offset(stickerBottomToTitle);
                make.right.equalTo(btn).offset(stickerRightToTitle);
                make.size.mas_equalTo(size);
            }];
        }
        
        if (!self.hiddenLine)
        {
            [self addSubview:self.lineView];
            CGSize size = self.lineSizeBlock ? self.lineSizeBlock() : CGSizeMake(49 * MS_ADAPTATION_RATIO, 6 * MS_ADAPTATION_RATIO);
            UIColor *lineColor = self.lineColorBlock ? self.lineColorBlock() : MS_HEX_COLOR(0x5ED3D2);
            UIImage *lineImage = self.lineImageBlock ? self.lineImageBlock() : nil;
            self.lineView.backgroundColor = lineColor;
            self.lineView.layer.contents = (id)lineImage.CGImage;
            CGFloat line_cornerRadii = self.lineCornerRadiiBlock ? self.lineCornerRadiiBlock() : 0;
            if (line_cornerRadii > 0)
            {
                [subBtn ms_makeChains:^(MSChainMaker * _Nonnull make) {
                   
                    make.ms_cornerRadii(line_cornerRadii);
                }];
            }
            [self.lineView mas_remakeConstraints:^(MASConstraintMaker *make) {
                
                make.size.mas_equalTo(size);
                make.centerX.equalTo(btn);
                if (self.hiddenSubtitle)
                {
                    make.top.equalTo(btn.mas_bottom).offset(self.lineToTitleOrSubTitleSpacingBlock ? self.lineToTitleOrSubTitleSpacingBlock() : 8 * MS_ADAPTATION_RATIO);
                }
                else
                {
                    make.top.equalTo(subBtn.mas_bottom).offset(self.lineToTitleOrSubTitleSpacingBlock ? self.lineToTitleOrSubTitleSpacingBlock() : 8 * MS_ADAPTATION_RATIO);
                }
            }];
        }
        
        [self setNeedsLayout];
        [self layoutIfNeeded];
        //滑动到中间
        if (self.autoScrollToCenter)
        {
            CGFloat x = CGRectGetMidX(btn.frame);
            CGFloat width = CGRectGetWidth(self.frame);
            CGFloat contentSize_width = MAX(self.contentSize.width, width);
            if (x - width / 2.0 <= 0)
            {
                [self setContentOffset:CGPointMake(0, 0) animated:YES];
            }
            else if (x - width / 2.0 >= contentSize_width - width)
            {
                [self setContentOffset:CGPointMake(contentSize_width - width, 0) animated:YES];
            }
            else
            {
                [self setContentOffset:CGPointMake(x - width / 2.0, 0) animated:YES];
            }
        }
    }
}


#pragma mark - getter
- (UIView *)stickersView
{
    if (!_stickersView)
    {
        _stickersView = [[UIView alloc] init];
    }
    
    return _stickersView;
}
- (UIView *)lineView
{
    if (!_lineView)
    {
        _lineView = [[UIView alloc] init];
        _lineView.backgroundColor = MS_HEX_COLOR(0x5ED3D2);
    }
    
    return _lineView;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
